// ==UserScript==
// @name         Ghost Editor Helper
// @namespace    http://your.homepage/
// @version      0.1
// @description  enter something useful
// @author       Bob
// @match        http://*.sudodev.cn/ghost/editor/*
// @grant        none
// ==/UserScript==

var getWeiXinPublishedMd = function() {
    var i = 1;
    var matchList = [];

    var raw = document.querySelector('.entry-markdown-content textarea').value;
    //convert highlight cods format
    var regHightLightCvt = /```\s?language-(.*?)\s+.*?\n/gi;
    raw = raw.replace(regHightLightCvt, '```\n');


    var replaceFn = function(match, p1, p2) {
        var matchObj = {
            match: match,
            url: p2
        };
        matchList.push(matchObj);
        return match + "<sup>" + (i++) + "</sup>";
    };
    //convert links
    var reg = /\[(.*?)\]\((https?:\/\/.*?)\)/gi;
    var processedStr = raw.replace(reg, replaceFn);
    var appendStrArr = [];
    appendStrArr.push('\n\n---\n<blockquote style="font-size:14px">文中标注链接：');
    for (var j = 0; j < matchList.length; j++) {
        appendStrArr.push((j + 1) + '：' + matchList[j].url);
    }

    var publishedStr = processedStr + appendStrArr.join('\n') + '</blockquote>';

    return publishedStr;
}

var registerBtn = function() {

    var id = 'cvtToWx';
    var a = '<a id="' + id + '" href="javascript:void(0)" style="\
float: right;\
border: 1px solid;\
padding: 2px;\
border-radius: 5px;\
margin-top: -3px;\
">转微信</a>';
    var floatingheader = document.querySelector('.floatingheader');
    floatingheader.innerHTML += a;
    document.getElementById(id).addEventListener('click', function() {
        var publishedStr = getWeiXinPublishedMd.call(null);
        console.log(publishedStr);
        window.$publishedStr = publishedStr;
        //copy(publishedStr);
    });


}

var dependencySelector = '.floatingheader';
var waitTimer = setInterval(function() {
    var header = document.querySelector(dependencySelector);
    if (header) {
        registerBtn();
        clearInterval(waitTimer);
    }
}, 1000);
